package com.zx.yixun.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.zx.yixun.data.ChooseOneBean;
import com.zx.ymy.base.Constant;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static com.blankj.utilcode.util.IntentUtils.getLaunchAppIntent;

/**
 * Created by Administrator on 2015/12/1.
 */
public class MyUtils {

    //格式化int类型的数据
    public static String price(int price){
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format(price);
        return format;
    }
    //格式化double类型的数据
    public static String price(double price){
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format(price);
        return format;
    }

    public static String priceAdd(double price1, double price2){
        DecimalFormat df = new DecimalFormat("0.00");
        BigDecimal bignum1 =new BigDecimal(price1);
        BigDecimal bignum2 =new BigDecimal(price2);
        bignum1 = bignum1.add(bignum2);

        String format = df.format(bignum1);
        return format;
    }
    //格式化为3位的double类型数据 tdd
    public static String tdd(double b){
        DecimalFormat df = new DecimalFormat("0.000");
        String format = df.format(b);
        return format;
    }

    /**
     * double类型如果小数点后为零显示整数否则保留 返回String
     * @param num
     * @return
     */
    public static String doubleTrans(double num){
        if(num % 1.0 == 0){
            return String.valueOf((int) num);
        }
        return String.valueOf(new DecimalFormat("#0.00").format(num));
    }

    public static String doubleTrans(String num){
        double Number;
        try {
            if (TextUtils.isEmpty(num)) {
                Number = 0;
            }else{
                Number = Double.parseDouble(num);
            }
            if(Number % 1.0 == 0){
                return String.valueOf((int) Number);
            }
            return String.valueOf(new DecimalFormat("#0.00").format(Number));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String times(){
        SimpleDateFormat formatter    =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate    =   new Date(System.currentTimeMillis());//获取当前时间
        String str    =    formatter.format(curDate);
        return str;
    }

    public static String times(long time){
        SimpleDateFormat formatter    =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate    =   new Date(time);//获取当前时间
        String str    =    formatter.format(curDate);
        return str;
    }

    public static String timesday(long time){
        SimpleDateFormat formatter    =   new SimpleDateFormat("yyyy-MM-dd");
        Date curDate    =   new Date(time);//获取当前时间
        String str    =    formatter.format(curDate);
        return str;
    }

    public static String getCovertTime(String time){
        SimpleDateFormat formatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date = formatter.parse(time);
            String str = date2Str(date,"yyyy-MM-dd HH:mm");
            return str;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    //当前时间过了多少秒
    public static int dayOverTime(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date d=new Date();
        String curtime = simpleDateFormat.format(d);
        Date date = null;
        try {
            date = simpleDateFormat.parse(curtime);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        String hh = date2Str(date,"HH");
        String mm = date2Str(date,"mm");
        String ss = date2Str(date,"ss");
        int seconds = Integer.parseInt(hh)*60*60;
        seconds = seconds +(Integer.parseInt(mm)*60);
        seconds = seconds+ Integer.parseInt(ss);
        return seconds;
    }

    public static String getSightCalendarCovertTime(Date date, int days){
        SimpleDateFormat formatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String week = date2ChinaWeek(date,"c");
        String month = date2Str(date,"MM");
        String day = date2Str(date,"dd");
        if(days==0){
            week = "今天";
        }else if(days==1){
            week = "明天";
        }
        return week+" " + month+"-"+day;
    }

    public static String getWeek(String time){
        SimpleDateFormat formatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if(StringUtils.isEmpty(time)){
            return "";
        }
        Date date = strTodate(time);
        String week = date2ChinaWeek(date,"c");
        return week;
    }

    /**
     * 获取几天后的date
     * @param days
     * @param d
     * @return
     */
    public static Date getLaterDay(int days, Date d){
        long addTime=1;   //以1为乘以的基数
        addTime*=days;   //1天以后   （如果是30天以后，则这里是30）
        addTime*=24;   //1天24小时
        addTime*=60;   //1小时60分钟
        addTime*=60;   //1分钟60秒
        addTime*=1000;   //1秒=1000毫秒
        //用毫秒数构造新的日期
        Date date=new Date(d.getTime()+addTime);
        return date;   //返回结果
    }

    public static Date longToDate(long lo) {
        Date date = new Date(lo);
        return date;
    }

    public static Date strTodate(String time){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dateToString(Date date, String df){
        SimpleDateFormat sd = new SimpleDateFormat(df);
        return sd.format(date);
    }

    //当前时间往后的时间
    public static Date getNextDay(int days){
        long addTime=1;   //以1为乘以的基数
        addTime*=days;   //1天以后   （如果是30天以后，则这里是30）
        addTime*=24;   //1天24小时
        addTime*=60;   //1小时60分钟
        addTime*=60;   //1分钟60秒
        addTime*=1000;   //1秒=1000毫秒
        //用毫秒数构造新的日期
        Date d=new Date();
        Date date=new Date(d.getTime()+addTime);
        return date;   //返回结果
    }

    public static String date2ChinaWeek(Date date, String format){
        if(date!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(date);
        }else{
            return "";
        }
    }

    public static String date2Str(Date date, String format){
        if(date!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }else{
            return "";
        }
    }
    /*
     *时间换算
     */
    public static String timedata(String time){
        //2015/11/6 10:05:52
        Calendar c = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format_info = new SimpleDateFormat("MM-dd");
        Date date = null;
        try {
            date = format.parse(time);
            c.setTime(date);
            long times= System.currentTimeMillis()-c.getTimeInMillis();
//            Log.d("chh","times:"+times);
            if(times>60*60*24*1000){
//                Log.d("chh","times 天:"+(times/(60*60*24*1000)));
                if((times/(60*60*24*1000))>30){
//                    Log.d("chh","times 月:"+(times/(60*60*24*1000)/30));
                    return ((times/(60*60*24*1000)/30)>3?"3":(times/(60*60*24*1000)/30))+"个月前";
//                    return format.format(c.getTimeInMillis()).split(" ")[0];
                }else{
                    return (times/(60*60*24*1000))+"天前";
                }
            }else if(times>60*60*1000){
                return (times/(60*60*1000))+"小时前";
            }else if(times>60*1000){
                return (times/(60*1000))+"分钟前";
            }else{
                return "刚刚";
            }
        } catch (Exception e) {
            return "未知";
        }
    }

    //格式化时间
    public static String timeFormat(long duration){
        long seconds = duration / 1000;
        long min = seconds / 60;
        int hour = (int)(min / 60);
        int m = (int) (min % 60);
        int s = (int) (seconds % 60);
        return ((hour<10)? "0"+hour : ""+hour+"")+":"+((m<10)? "0"+m : ""+m+"")+":"+((s<10)? "0"+s : ""+s+"");
    }

    /**
     * 格式化毫秒值，如果这个毫秒值包含小时，则格式为时分秒，如:01:30:58，如果不包含小时，则格式化为分秒，如：30:58
     * @param duration
     * @return
     */
    public static CharSequence formatMillis(long duration) {
        Calendar calendar = Calendar.getInstance(); // 以当前系统时间创建一个日历
        calendar.clear();   // 清空时间，变成1970 年 1 月 1 日 00:00:00
        calendar.add(Calendar.MILLISECOND, (int) duration);// 1970 年 1 月 1 日 01:58:32
        boolean hasHour = duration / (1 * 60 * 60 * 1000) > 0;    // 判断毫秒值有没有包含小时
        CharSequence inFormat = hasHour ? "kk:mm:ss" : "mm:ss";   // 如果包含小时，则格式化为时:分:秒，否则格式化为分:秒
        return DateFormat.format(inFormat, calendar);
    }

    //邮箱验证
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    /**
     * 手机号中间四位的替换处理
     * @param phone
     * @return
     */
    public static String PhoneNumberFourCenter(String phone){
        if (phone.isEmpty()) {
            return "";
        }else if(phone.length()!=11){
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
    }

    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    /*public static String getNewContent(String htmltext){
        try {
            Document doc= Jsoup.parse(htmltext);
            Elements elements=doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width","100%").attr("height","auto");
            }
            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }*/

    /**
     * 设置含html标签的String字符串
     * @param content
     * @return
     */
    public static String setHtmlString(String content){
        String result = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //其中的flags表示：
            //FROM_HTML_MODE_COMPACT：html块元素之间使用一个换行符分隔
            //FROM_HTML_MODE_LEGACY：html块元素之间使用两个换行符分隔
            result = Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT).toString();
        } else {
            result = Html.fromHtml(content).toString();
        }
        return result;
    }

    /**
     * 限制小数点后两位小数
     */
    public static void setPricePoint(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 限制小数点后一位小数
     */
    public static void setOnePoint(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 1) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 2);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     *EditText中获取焦点输入框内容为0时清空 （输入必须是数字）
     */
    public static void setEditTextEmpty(final EditText editText){
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("chh","------------------onFocusChange2"+hasFocus);
                if (hasFocus&&!editText.getText().toString().equals("")&& Double.parseDouble(editText.getText().toString())==0) {
                    editText.setText("");
                }
            }
        });
    }

    /**
     * 获取焦点后，光标置于末尾
     */
    public static void setEditSelection(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().isEmpty()) {
                    editText.setSelection(s.toString().length());
                }
            }
        });
    }

    /**
     * 打开软键盘
     */
    public static void openKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 关闭软键盘
     */
    public static void closeActivityKeybord(Activity activity) {
        if (KeyboardUtils.isSoftInputVisible(activity)) {
            KeyboardUtils.toggleSoftInput();
        }
    }

    /**
     * 格式化时间 （年-月-日  时）
     */
    public static String FormatTime(String time){
       return time.equals("")||time.length()<13?"":time.substring(0,11)+"("+ Integer.parseInt(time.substring(11,13))+"点)";
    }

    /**
     * 格式化时间 （年-月-日  时）
     */
    public static String FormatTime2(String time){
        Date date = strToDateLong(time);
        if(date==null){
            return time;
        }
        return dateToStr(date);
    }

    /**
     *
     * @return
     */
    public static Date StrToDate(String timestr, SimpleDateFormat simpleDateFormat) {
        try {
            Date date= simpleDateFormat.parse(timestr);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param dateDate
     * @return
     */
    public static String dateToStr(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     * @param strDate
     * @return
     */
     public static Date strToDateLong(String strDate) {
         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
         Date strtodate = null;
         try {
             strtodate = formatter.parse(strDate);
         } catch (ParseException e) {
             e.printStackTrace();
         }
         return strtodate;
     }

    /**
     * 将long类型的时间转换为日-时-分
     */
    public static String ToDayHourMinute(long time){
        int time1 = (int) (time/(1000*60));//分
        if (time1==60) {
            return "0-1-0";
        }else if(time1<60){
            return "0-0-"+time1;
        }else{
            int time2 = time1/60;//时
            int time3 = time1%60;//分
            if (time2==24) {
                return "1-0-"+time3;
            }else if(time2<24){
                return "0-"+time2+"-"+time3;
            }else{
                int time4 = time2/24;//天
                int time5 = time2%24;//时
                return time4+"-"+time5+"-"+time3;
            }
        }
    }

    /**
     * 将long类型的时间转换为日-时-分-秒
     */
    public static String ToDayHourMinuteSecond(long time){
        int time1 = (int) (time/(1000*60));//分
        int time0 = (int) ((time%(1000*60))/1000);//秒
        if (time1==60) {
            return "0-1-0-"+time0;
        }else if(time1<60){
            return "0-0-"+time1+"-"+time0;
        }else{
            int time2 = time1/60;//时
            int time3 = time1%60;//分
            if (time2==24) {
                return "1-0-"+time3+"-"+time0;
            }else if(time2<24){
                return "0-"+time2+"-"+time3+"-"+time0;
            }else{
                int time4 = time2/24;//天
                int time5 = time2%24;//时
                return time4+"-"+time5+"-"+time3+"-"+time0;
            }
        }
    }

    /**
     * 自定义String字符串中某一段字符的颜色
     */
    public static String ColorText(String color, String Content){
        return "<font color = '"+color+"'>"+Content+"</font>";
    }

    /**
     * 自定义String字符串中某一段字符的颜色和字体大小
     */
    public static String ColorAndSizeText(String color, String Content, String size){
        return "<font color = '"+color+"' size = '"+size+"'>"+Content+"</font>";
    }

    /**
     *同时改变字符串中的字体大小和颜色
     * @return
     */
    public static SpannableStringBuilder sizeAndColor(String cotent, int color, int size, int start, int end){
        ColorStateList colors = ColorStateList.valueOf(color);//0xffff0000
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(cotent);
        //style 为0 即是正常的，还有Typeface.BOLD(粗体) Typeface.ITALIC(斜体)等
        //size  为0 即采用原始的正常的 size大小
        spanBuilder.setSpan(new TextAppearanceSpan(null, 0, size, colors, null), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

//        TextView tv_test = (TextView) findViewById(R.id.tv_test);
//        tv_test.setText(spanBuilder);
        return spanBuilder;
    }

    /**
     * 判断网络连接是否可用
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     *equals比较对象
     *constant 常量
     *obj 被比较的对象
     */
    public static boolean toEquals(Object constant, Object obj){
        if (constant==null||obj==null) {
            new NullPointerException("Object为null");
        }else{
            return constant.equals(obj);
        }
        return false;
    }

    /**
     <xliff:g>标签介绍：属性id可以随便命名   属性值举例说明  %1$d  &2$d
     %n$ms：代表输出的是字符串，n代表是第几个参数，设置m的值可以在输出之前放置空格
     %n$md：代表输出的是整数，n代表是第几个参数，设置m的值可以在输出之前放置空格，也可以设为0m,在输出之前放置m个0
     %n$mf：代表输出的是浮点数，n代表是第几个参数，设置m的值可以控制小数位数，如m=2.2时，输出格式为00.00
     也可简单写成： %s（表示字符串）    %d（表示整数）    %f（表示浮点数）
     */
    public static String intFormat(String format, int num){
        return String.format(format, num);
    }
    public static String strFormat(String format, String content){
        return String.format(format, content);
    }

    /**
     * 信息太长,分段打印
     * @param tag
     * @param msg
     */
    public static void i(String tag, String msg) {
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001 - tag.length();
        //大于4000时
        while (msg.length() > max_str_length) {
            Log.i(tag, msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        Log.i(tag, msg);
    }


    /**
     *将object转为string字符串
     * @param src
     * @return
     */
    public static String ToJsonString(Object src){

        return new Gson().toJson(src);
    }


    /**
     * 非空判断
     * @param str
     */
    public static String NoEmptyString(String str){
        if (str==null) {
            return "";
        }else{
            return str;
        }
    }
    /**
     * 获取 Glide options
     * @param resourceid 图片资源id
     * @return
     */
    public static RequestOptions GetOptions(int resourceid){
        RequestOptions options = new RequestOptions()
                .placeholder(resourceid)//图片加载出来前，显示的图片
                .fallback(resourceid) //url为空的时候,显示的图片
                .error(resourceid);//图片加载失败后，显示的图片
        return options;
    }

    /**
     * map 根据value值获取key值
     * @param map
     * @param value
     * @return
     */
    public static Object getKey(Map map, Object value){
        Object object=null;
        for(Object key: map.keySet()){
            if(map.get(key).equals(value)){
                object = key;
            }
        }
        return object;
    }

    /*
     * 检查手机上是否安装了指定的软件
     * @param context
     * @param packageName：应用包名
     * @return
      */
    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }


    /*
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     * @param phoneNum 电话号码
     */
    public static void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    /*
     *string字符串能否转变成int类型
     */
    public static boolean canParseInt(String str){
        if(str == null){ //验证是否为空
            return false;
        }
        return str.matches("\\d+"); //使用正则表达式判断该字符串是否为数字，第一个\是转义符，\d+表示匹配1个或 //多个连续数字，"+"和"*"类似，"*"表示0个或多个
    }

    /*
    *判断字符串是否为纯数字
    * */
    public static boolean strIsAllNumber(String str){
        return str.matches("[0-9]+");
    }

    /*
     * 设置 View 的图片的大小和位置
     * @param context
     * @param view
     * @param drawableId  图片id
     * @param withHight  图片大小 单位：dp
     * @param poi  图片位于view的位置  0：左 1：上 2：右 3：下
     * @param drawablePadding  图片的padding距离  单位：dp
     */
    public static void ImageChange(Context context, View view, int drawableId, int withHight, int poi, int drawablePadding){
        Drawable drawable = context.getResources().getDrawable(drawableId);
        // setBounds的参数就是两个坐标，左上和右下，View有默认的坐标位置，{0,0,20,20}就表示左上角不动，宽高为20，如果{10，10，30，30}就表示View的绘制起点往右偏了10，宽高为20
        drawable.setBounds(0, 0, SizeUtils.dp2px(withHight), SizeUtils.dp2px(withHight));
        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            textView.setCompoundDrawables(poi==0?drawable:null, poi==1?drawable:null, poi==2?drawable:null, poi==3?drawable:null);
            textView.setCompoundDrawablePadding(SizeUtils.dp2px(drawablePadding));
        } else if (view instanceof Button) {
            Button button = (Button) view;
            button.setCompoundDrawables(poi==0?drawable:null, poi==1?drawable:null, poi==2?drawable:null, poi==3?drawable:null);
            button.setCompoundDrawablePadding(SizeUtils.dp2px(drawablePadding));
        }
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (info.baseActivity.getPackageName().equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否为汉字
     * @param string
     * @return
     */

    public static boolean isChinese(String string) {
        int n = 0;
        for (int i = 0; i < string.length(); i++) {
            n = (int) string.charAt(i);
            if (!(19968 <= n && n < 40869)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符串是否仅为数字:
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置字体加粗、常规  type:0常规   1:加粗
     * @param textView
     */
    public static void setTextType(TextView textView, int type){
        if (type == 0) {
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));//常规
        } else {
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
        }
    }

    /**
     *集合列表对象转换
     * @return
     */
    /**
     * 将JSON字符串转换为集合
     *
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> JsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    //空数据返回“无”
    public static String EmptyToString(String content){
        if (content == null || content.isEmpty()) {
            return "无";
        } else {
            return content;
        }
    }


    /**
     * 保存图片到本地并更新图片库
     * @param context
     * @param bmp
     */
    public static void saveToSystemGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File fileDir = new File(Environment.getExternalStorageDirectory(), Constant.SaveFileImagePath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(fileDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
//        sendBroadcast(intent);
        //图片保存成功，图片路径：
        Toast.makeText(context,"图片保存路径：" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    //检测是否安装应用
    public static boolean hasApplication(Context context, String packageName){
        PackageManager packageManager = context.getPackageManager();
        //获取系统中安装的应用包的信息
        List<PackageInfo> listPackageInfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < listPackageInfo.size(); i++) {
            if(listPackageInfo.get(i).packageName.equalsIgnoreCase(packageName)){
                return true;
            }
        }
        return false;
    }

    //安装apk
    public static  void installApk(Context context, String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
//        L.i("安装路径=="+downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, AppUtils.getAppPackageName()+".fileprovider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);

    }

    private static final int MIN_DELAY_TIME= 200;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;
    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }


//    //重启应用
//    public static void lunchApp(){
//        Intent intent = getLaunchAppIntent(Utils.getApp().getPackageName(), true);
//        if (intent == null) {
//            Log.e("AppUtils", "Didn't exist launcher activity.");
//            return;
//        }
//        intent.addFlags(
//                Intent.FLAG_ACTIVITY_NEW_TASK
//                        | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
//        );
//        Utils.getApp().startActivity(intent);
//    }


    //拷贝List数组
    public static <E> List<E> deepCopy(List<E> src) {
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(src);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            @SuppressWarnings("unchecked")
            List<E> dest = (List<E>) in.readObject();
            return dest;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<E>();
        }
    }


    public static List<ChooseOneBean> covertBean(String data){
        return new Gson().fromJson(data, new TypeToken<List<ChooseOneBean>>(){}.getType());
    }


    /**
     * 计算CRC16校验码
     *
     * @param bytes 需要计算的字节数组
     */
    public static String getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        String s = Integer.toHexString(CRC);
        while (s.length()<4){
            s="0"+s;
        }
        return s.substring(2,4).toUpperCase()+" "+s.substring(0,2).toUpperCase();
    }

    /**
     * 十六进制转字节数组
     * @param hexString
     * @return
     */
    public static byte[] decodeHexString(String hexString) {
        if (hexString.length() % 2 == 1) {
            throw new IllegalArgumentException(
                    "Invalid hexadecimal String supplied.");
        }
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
        }
        return bytes;
    }

    /**
     * 十六进制转byte字节
     * @param hexString
     * @return
     */
    public static byte hexToByte(String hexString) {
        int firstDigit = toDigit(hexString.charAt(0));
        int secondDigit = toDigit(hexString.charAt(1));
        return (byte) ((firstDigit << 4) + secondDigit);
    }

    private static  int toDigit(char hexChar) {
        int digit = Character.digit(hexChar, 16);
        if(digit == -1) {
            throw new IllegalArgumentException(
                    "Invalid Hexadecimal Character: "+ hexChar);
        }
        return digit;
    }



    /**
     * ASCII码转换为16进制
     * @param str
     * @return
     */
    public static String convertStringToHex(String str){
        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString((int)chars[i]));
        }

        return hex.toString();
    }

}
